import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import axios from '../axios'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))

  const isAuthenticated = computed(() => !!token.value)

  const login = async (username: string, password: string) => {
    try {
      const resp = await axios.post('/auth/login', { username, password })

      token.value = resp.data.token
      localStorage.setItem('token', token.value ?? '')
    } catch (error) {
      console.error('login Error', error)
    }
  }

  const register = async (username: string, password: string) => {
    try {
      const resp = await axios.post('/auth/register', { username, password })

      token.value = resp.data.token
      localStorage.setItem('token', token.value ?? '')
    } catch (error) {
      console.error('register Error', error)
    }
  }

  const logout = () => {
    token.value = null
    localStorage.removeItem('token')
  }
  return {
    token,
    login,
    register,
    logout,
    isAuthenticated,
  }
})
